package com.ylg.mybatis.core;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @since 1.0
 * @author 杨凌广
 * @version 1.0
 *
 * jdbc事务管理器的实现
 */
public class JdbcTransaction implements Transaction{

    private DataSource dataSource;

    private Connection connection;

    private boolean auto;

    public JdbcTransaction(DataSource dataSource, boolean auto) {
        this.dataSource = dataSource;
        this.auto = auto;
    }

    @Override
    public DataSource getDataSource() {
        return dataSource;
    }

    @Override
    public void close() {

        try {
            getConnection().close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void commit() {
        try {
            getConnection().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void rollback() {
        try {
            getConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Connection getConnection() {
        return connection;
    }

    @Override
    /**
     * 如果数据源已经打开一次，就不需要重新创建。
     */
    public void openConnection() {
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
                connection.setAutoCommit(auto);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
